# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

my.test <- function(formula, data, method, paired) {
  p <- 1
  if (method == "wilcox.test") {
    test <- wilcox.test(formula = formula, data = data, paired = paired)
    p <- test$p.value
  }else {
    test <- kruskal.test(formula = formula, data = data)
    p <- test$p.value
  }
  list(p = p)
}


library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(tidyverse)
library(scales)
library(magrittr)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

configData

isPaired <- configData["isPaired", "value"] == "T"

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  mutate(ClassNote = as.character(ClassNote))

parent <- "./"
createWhenNoExist(parent)
fileName <- paste0(parent, "/PCA_Score_with_Boxplot_with_Points.pdf")

pdf(fileName, width = 9, height = 8)

pcDataFileName <- paste0(parent, "/PCA_Score.csv")
pc12 <- read_csv(pcDataFileName) %>%
  rename(SampleID = X1) %>%
  select(c("SampleID", "PC1", "PC2")) %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(sampleInfo$ClassNote))) %>%
  arrange(ClassNote)

print(pc12)

if (isPaired) {
  pc12 <- pc12 %>%
    arrange(Pair_ID)
}

pc12

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

parameterData

impoPc1 <- parameterData[1, "PC1"]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- parameterData[1, "PC2"]
impoPc2 <- round(impoPc2 * 100, 2)

top <- 0.2
left <- 0.3
right <- 0.2

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
  select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
  deframe()

sampleCols

p <- ggplot(pc12, mapping = aes(x = PC1, y = PC2)) +
  xlab(paste("PC1(", impoPc1, "%)", sep = "")) +
  ylab("") +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 11, vjust = 0.5), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.text.y = element_text(size = 11, angle = 90), legend.position = "none",
        axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12),
        panel.border = element_rect(size = 0.75), plot.margin = unit(c(top, right, 0.5, left), "cm")
  ) +
  #0 line
  geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  #point
  stat_ellipse(colour = "#BEBEBE", size = 0.3, level = 0.95, type = "norm") +
  geom_point(aes(colour = factor(ClassNote)), size = 4, stroke = 0) +
  #lengend
  scale_colour_manual("", values = sampleCols)

axisInfo <- ggplot_build(p)$layout$panel_params[[1]]
ylabels <- axisInfo$y.labels
yBreaks <- ylabels %>% as.numeric()
ylim <- axisInfo$y.range
xlabels <- axisInfo$x.labels
xBreaks <- xlabels %>% as.numeric()
xlim <- axisInfo$x.range

isMulti <- length(unique(pc12$ClassNote)) > 2

method <- if (isMulti) {
  "kruskal.test"
}else "wilcox.test"
pBeforeStr <- ""

rTest <- my.test(PC2 ~ ClassNote, data = pc12, method = method, paired = isPaired)
rPValue <- rTest$p %>% round(3)
if (rPValue == 0) {
  rPValue <- rTest$p %>% scientific(digits = 3)
}

print(rPValue)
print("in")

rBoxPlot <- ggplot(pc12, mapping = aes(x = ClassNote, y = PC2, fill = ClassNote)) +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.y = element_text(size = 8.8), legend.position = 'none', axis.title.y = element_text(size = 11),
        legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'), legend.text = element_text(size = 6),
        axis.title.x = element_text(size = 12), panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.ticks.x = element_blank(), panel.border = element_rect(size = 0.75),
        plot.margin = unit(c(top, right, 0.5, left), "cm")
  ) +
  geom_boxplot() +
  geom_jitter() +
  #lengend
  scale_fill_manual("", values = sampleCols) +
  scale_x_discrete(paste0(pBeforeStr, "Pvalue=", rPValue), labels = rep("", length(pc12$ClassNote)), breaks = pc12$ClassNote) +
  scale_y_continuous(str_c("PC2(", impoPc2, "%)"), limits = ylim, expand = c(0, 0))

ggplot_build(p)$layout$panel_params

bTest <- my.test(PC1 ~ ClassNote, data = pc12, method = method, paired = isPaired)
bPValue <- bTest$p %>% round(3)
if (bPValue == 0) {
  bPValue <- bTest$p %>% scientific(digits = 3)
}

bBoxPlot <- ggplot(pc12, mapping = aes(x = ClassNote, y = PC1, fill = ClassNote)) +
  xlab("") +
  ylab("") +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 9, vjust = 0.5), panel.border = element_rect(size = 0.75),
        axis.text.y = element_blank(), legend.position = 'none', axis.ticks.y = element_blank(),
        axis.title.y = element_text(size = 12), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 6), axis.title.x = element_text(size = 12), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), plot.title = element_text(size = 12),
        plot.margin = unit(c(top, right, 0.5, left), "cm")
  ) +
  geom_boxplot() +
  geom_jitter() +
  coord_flip() +
  scale_fill_manual("", values = sampleCols) +
  ggtitle(paste0(pBeforeStr, "Pvalue=", bPValue)) +
  scale_y_continuous("", limits = xlim, expand = c(0, 0))


legend <- g_legend(p + theme(legend.position = 'left', legend.text = element_text(size = 10),
                             legend.margin = margin(t = -2, unit = 'cm'))
)

gA <- ggplotGrob(p)
gB <- ggplotGrob(bBoxPlot)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)

grid.arrange(gA, rBoxPlot, gB, legend, ncol = 2, widths = c(0.75, 0.25), heights = c(0.75, 0.25), newpage = F)

dev.off()
